<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter之StatefulWidget与性能》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="早起的年轻人做的网站"><meta property="og:title" content="《Flutter之StatefulWidget与性能》" />
<meta property="og:description" content="
本文主要介绍Flutter StatefulWidget 与应用性能其实有些微妙的联系。
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" />
<meta property="og:image" content="https://luckly.work/logo.png"/>
<meta property="article:published_time" content="2021-07-31T21:08:33+08:00" />
<meta property="article:modified_time" content="2021-07-31T21:08:33+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://luckly.work/logo.png"/>

<meta name="twitter:title" content="《Flutter之StatefulWidget与性能》"/>
<meta name="twitter:description" content="
本文主要介绍Flutter StatefulWidget 与应用性能其实有些微妙的联系。
"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" /><link rel="prev" href="https://luckly.work/flutter%E4%B9%8Brenderobject%E6%B5%85%E6%9E%90/" /><link rel="next" href="https://luckly.work/flutterperformance%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%E7%AE%80%E4%BB%8B/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter之StatefulWidget与性能》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD\/"
        },"image": [{
                            "@type": "ImageObject",
                            "url": "https:\/\/luckly.work\/images\/Apple-Devices-Preview.png",
                            "width":  3200 ,
                            "height":  2048 
                        }],"genre": "posts","keywords": "flutter","wordcount":  931 ,
        "url": "https:\/\/luckly.work\/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD\/","datePublished": "2021-07-31T21:08:33+08:00","dateModified": "2021-07-31T21:08:33+08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": {
                    "@type": "ImageObject",
                    "url": "https:\/\/luckly.work\/images\/avatar.png",
                    "width":  528 ,
                    "height":  560 
                }},"author": {
                "@type": "Person",
                "name": "早起的年轻人"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">Lucklyの博客 - 在阅读中遇见自己</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/posts/">所有文章</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/flutter/">Flutter</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/read/">读书笔记</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/go/">Go</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/tags/">标签</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/">分类</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="https://github.com/ITmxs">Github</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/friend/">友链</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter之StatefulWidget与性能》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>早起的年轻人</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 931 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 2 分钟&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#总结">总结</a></li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍Flutter StatefulWidget 与应用性能其实有些微妙的联系。</p>
</blockquote>
<p>Flutter 官方文档提到 widget 只是一个配置数据结构，创建是非常轻量的，加上 Flutter 团队对 widget 的创建/销毁做了优化，不用担心整个 widget 树重新创建所带来的性能问题。但实际上并非这么简单。看看这篇文章怎么说吧。</p>
<p>本文翻译自 <a href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations" target="_blank" rel="noopener noreffer">Performance considerations</a>。</p>
<p>有两大类 <a href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html" target="_blank" rel="noopener noreffer">StatefulWidget</a>。</p>
<p>一类 StatefulWidget 在 <a href="https://api.flutter.dev/flutter/widgets/State/initState.html" target="_blank" rel="noopener noreffer">State.initState</a> 方法中分配资源，并且在 <a href="https://api.flutter.dev/flutter/widgets/State/dispose.html" target="_blank" rel="noopener noreffer">State.dispose</a> 方法中释放资源，但并不依赖 <a href="https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html" target="_blank" rel="noopener noreffer">InheritedWidget</a> 或调用 <a href="https://api.flutter.dev/flutter/widgets/State/setState.html" target="_blank" rel="noopener noreffer">State.setState</a> 方法。这类 Widget 通常用于应用或页面的根节点，并且使用 <a href="https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html" target="_blank" rel="noopener noreffer">ChangeNotifier</a>、<a href="https://api.flutter.dev/flutter/dart-async/Stream-class.html" target="_blank" rel="noopener noreffer">Stream</a> 或其他对象来跟子节点通信。遵守这种模式的 StatefulWidget 在 CPU 和 GPU 上的开销相对较低，因为它们只被创建一次且不再更新。所以这种 StatefulWidget 可以有相对复杂和较深层级的 build 方法。</p>
<p>另一类 StatefulWidget 使用 <a href="https://api.flutter.dev/flutter/widgets/State/setState.html" target="_blank" rel="noopener noreffer">State.setState</a> 方法或依赖 <a href="https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html" target="_blank" rel="noopener noreffer">InheritedWidget</a>。这类 widget 通常在应用的生命周期中重建很多次，因此最小化其重建过程非常重要。(它们可能也会在 <a href="https://api.flutter.dev/flutter/widgets/State/initState.html" target="_blank" rel="noopener noreffer">State.initState</a> 或 <a href="https://api.flutter.dev/flutter/widgets/State/didChangeDependencies.html" target="_blank" rel="noopener noreffer">State.didChangeDependencies</a> 方法中分配资源，但重点在于<strong>重建</strong>)</p>
<p>有若干技巧用来减小重建 StatefulWidget 对性能的影响：</p>
<ul>
<li>将状态下沉到叶子节点。比如，页面上有个时钟，与其将时间状态放在上层页面中(每次时间更新时重建整个页面)，不如创建一个专用的 clock widget (每次时间更新时仅仅只需更新这个 widget)</li>
<li>最小化 build 方法创建的 widget 的数量以及相对应的 node 数量。理想状态下，一个 StatefulWidget 只用创建唯一一个 widget (类型为 <a href="https://api.flutter.dev/flutter/widgets/RenderObjectWidget-class.html" target="_blank" rel="noopener noreffer">RenderObjectWidget</a>)。(显然这并不总是可行，但 widget 越接近这个理想状态则越高效)</li>
<li>如果一棵子树并不变化，缓存对应的 widget 并尽可能复用。复用一个 widget 比新生成一个 widget 要高效。一种常用的改进方式是，重构有状态的部分到一个接收 child 参数的 widget 中</li>
<li>尽可能使用 <code>const</code> widget (这等同于缓存和复用 widget)</li>
<li>避免改变已创建的子树的深度或修改子树中 widget 的类型。比如，与其直接返回子节点或将其包裹在 <a href="https://api.flutter.dev/flutter/widgets/IgnorePointer-class.html" target="_blank" rel="noopener noreffer">IgnorePointer</a>，不如总是将子节点包裹在 <a href="https://api.flutter.dev/flutter/widgets/IgnorePointer-class.html" target="_blank" rel="noopener noreffer">IgnorePointer</a> 并且操作 <a href="https://api.flutter.dev/flutter/widgets/IgnorePointer/ignoring.html" target="_blank" rel="noopener noreffer">IgnorePointer.ignoring</a> 属性值。原因是改变子树深度会导致重新 build/layout/paint 整个子树，而修改属性值只会对渲染树进行尽可能少的修改 (在 <a href="https://api.flutter.dev/flutter/widgets/IgnorePointer-class.html" target="_blank" rel="noopener noreffer">IgnorePointer</a> 这个例子中，根本不必重新 layout 和 paint)</li>
<li>如果出于某些原因必须要改变深度，可以考虑将子树的通用部分包裹在一个带 <a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html" target="_blank" rel="noopener noreffer">GlobalKey</a> 的 widget 中 (该 GlobalKey 在 widget 生命周期中不变。如果其他 widget 不能很方便地设置 key，可考虑使用 <a href="https://api.flutter.dev/flutter/widgets/KeyedSubtree-class.html" target="_blank" rel="noopener noreffer">KeyedSubtree</a>)</li>
</ul>
<h1 id="总结">总结</h1>
<ul>
<li>减少 widget 重建 (可借助 Android Studio &gt; Flutter Performance &gt; Widget rebuild stats 来<a href="https://flutter.cn/docs/development/tools/android-studio#show-performance-data" target="_blank" rel="noopener noreffer">统计重建次数</a>)</li>
<li>缓存不变的子树</li>
<li>尽可能使用 <code>const</code> widget</li>
</ul></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" data-title="《Flutter之StatefulWidget与性能》" data-hashtags="flutter"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" data-hashtag="flutter"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Hacker News" data-sharer="hackernews" data-url="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" data-title="《Flutter之StatefulWidget与性能》"><i class="fab fa-hacker-news fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" data-title="《Flutter之StatefulWidget与性能》"><i data-svg-src="https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://luckly.work/flutter%E4%B9%8Bstatefulwidget%E4%B8%8E%E6%80%A7%E8%83%BD/" data-title="《Flutter之StatefulWidget与性能》" data-image="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/flutter%E4%B9%8Brenderobject%E6%B5%85%E6%9E%90/" class="prev" rel="prev" title="《Flutter之RenderObject浅析》"><i class="fas fa-angle-left fa-fw"></i>《Flutter之RenderObject浅析》</a>
            <a href="/flutterperformance%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%E7%AE%80%E4%BB%8B/" class="next" rel="next" title="《FlutterPerformance分析工具简介》">《FlutterPerformance分析工具简介》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">早起的年轻人</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/algoliasearch@4.2.0/dist/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"search":{"algoliaAppID":"PASDMWALPK","algoliaIndex":"index.zh-cn","algoliaSearchKey":"b42948e51daaa93df92381c8e2ac0f93","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
